`ifndef __INTERLEAVER__
`define __INTERLEAVER__

module interleaver (
           input clk2,
           input rst_n,
           input din,
           input din_valid,
           output dout,
           output dout_valid);

reg dout_reg;
reg dout_valid_reg;
reg [63: 0] interReg_0;
reg [63: 0] interReg_1;
reg now_chosen_write_reg;
reg [5: 0] input_cnt;
reg [5: 0] output_rest;

assign dout = (dout_valid_reg == 1) ? dout_reg : 1'bZ;
assign dout_valid = dout_valid_reg;

always @(posedge clk2 or negedge rst_n) begin
    if (rst_n == 0) begin
        now_chosen_write_reg <= 0;
        dout_reg <= 0;
        dout_valid_reg <= 0;
        input_cnt <= 0;
        output_rest <= 0;
        interReg_0 <= 0;
        interReg_1 <= 0;
    end
    else begin
        if (din_valid) begin
            // 选择器选择输入的寄存器组
            if (now_chosen_write_reg == 0) begin
                interReg_0[input_cnt] <= din;
            end
            else begin
                interReg_1[input_cnt] <= din;
            end

            // 如果输入计数达到了63，说明这一次已经对63号单元写入了，需要修改
            if (input_cnt == 63) begin
                // 由于计数要在下一个周期才能生效，因此这里要直接输出了
                input_cnt <= 0;
                dout_valid_reg <= 1;
                dout_reg <= (now_chosen_write_reg == 0) ? interReg_0[0] : interReg_1[0];
                if (output_rest == 0)
                    output_rest <= 63;
                else begin
                    
                end
                now_chosen_write_reg <= ~now_chosen_write_reg;
            end
            else begin
                input_cnt <= input_cnt + 1'b1;
            end
        end
        else begin

        end

        if (output_rest != 0) begin
            dout_reg <= (now_chosen_write_reg == 0) ?
                     interReg_1[((64 - output_rest) % 8) * 8 + (64 - output_rest) / 8]:
                     interReg_0[((64 - output_rest) % 8) * 8 + (64 - output_rest) / 8];
            output_rest <= output_rest - 1'b1;
        end
        else begin
            if (input_cnt != 63)
                dout_valid_reg <= 0; // 表明上一个数据没有传输完全，输出关闭
            else begin

            end
        end
    end
end

// endmodule
endmodule

`endif
